package com.bzchao.okhttpuploader;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Map;

import okhttp3.Call;

/**
 * Created by zhy on 15/icon_tmp/17.
 */
public class OkHttpRequestUtils {
    public static OkHttpRequestUtils MyHttpRequestUtil;
    public static Context m_context;

    private OkHttpRequestUtils(Context context) {
        m_context = context;
    }

    public static synchronized OkHttpRequestUtils getInstance(Context context) {
        if (MyHttpRequestUtil == null) {
            MyHttpRequestUtil = new OkHttpRequestUtils(context);
        }
        return MyHttpRequestUtil;
    }

    /**
     * 获取对应的String数据 使用post方法
     *
     * @param Url      方法地址
     * @param params   参数信息
     * @param callback 返回句柄
     */
    public synchronized void postFormData(String Url, Map<String, String> params, Callback callback) {
        OkHttpUtils
                .post()
                .url(Url)
                .params(params)
                .build()
                .connTimeOut(20000)
                .readTimeOut(20000)
                .writeTimeOut(20000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        Toast.makeText(m_context, "网络出错！", Toast.LENGTH_SHORT).show();
                        callback.onError(call, e);
                    }

                    @Override
                    public void onResponse(String response) {
                        Log.d("OkHttpRequestUtil", "success:" + response);
                        callback.onResponse(response);
                    }
                });
    }

}






